package org.smarthings.things.commons.rest;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;

@Provider
@Component(immediate = true)
@Service(CommonExceptionMapper.class)
public class CommonExceptionMapper implements ExceptionMapper<Throwable> {

	// TODO distinguish between missing wrong arguments and missing resource!
	// TODO use ThingErrorResource in response!
	public Response toResponse(Throwable t) {
		System.out.println("CommonExceptionMapper.toResponse()");
		t.printStackTrace();

		if (t instanceof IllegalArgumentException) {
			return Response.status(Response.Status.BAD_REQUEST).build();
		}
		if (t instanceof WebApplicationException) {
			WebApplicationException wae = (WebApplicationException) t;
			Response response = wae.getResponse();
			if (response != null) {
				return response;
			}
		}
		return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
	}

}
